<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: xajax.shopping_cart.php 397 2014-01-18 15:59:57Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 397 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2014-01-18 15:59:57 +0000 (Sat, 18 Jan 2014) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

require_once (DIR_FS_INC.'inc.get_tax_class_id.php');
require_once (DIR_FS_INC.'inc.get_attribute_prefix.php');
require_once (DIR_FS_INC.'inc.get_clean_id.php');
require_once (DIR_FS_INC.'inc.get_product_id.php');
require_once (DIR_FS_INC.'inc.get_shippingtime_functions.php');
require_once (DIR_FS_INC.'inc.array_get_item.php');

function delete($id) {
	$ajax = new xajaxResponse();

	$_SESSION['cart']->remove($id);

	if($_SESSION['cart']->count_contents() < 1) {
		$_SESSION['cart']->reset();
		$ajax->script('$(".headerInfo").fadeOut(900,function(){$(this).remove();});');
		$ajax->assign('cart_quantity', 'innerHTML', '<div id="cart_is_empty">'.CART_IS_EMPTY.'<br /><div class="ar"><a href="'.href_link(FILENAME_DEFAULT).'">'.image_button('button_continue.gif', IMAGE_BUTTON_CONTINUE).'</a></div></div>');
		//$ajax->script('setTimeout("delayer(\''.FILENAME_DEFAULT.'\');", 3000);'); // zur Startseite

	} else {
		$id = get_clean_id($id);
		$ajax->script('$EL(".p_'.$id.'").fadeOut(900,function(){$(this).remove();});');
		if(!empty($_SESSION['cart']->contents[$id]['attributes']))
			$ajax->script('$EL(".p_'.$id.'").fadeOut(900,function(){$(this).remove();});');
		$check = checkStock($id);
		if(empty($check['info']))
			$ajax->script('$(".headerInfo").fadeOut(900,function(){$(this).remove();});');
		$ajax->call('xajax_calculateTotal');
		$ajax->call('xajax_calculateShippingTime');
		$ajax->call('xajax_removeLoader');
	}

	return $ajax;
}

function minus($id) {
	global $price;

	$ajax = new xajaxResponse();
//print_r($_SESSION['cart']->contents); die();
	if($_SESSION['cart']->contents[$id]['qty'] > 1) {
		$_SESSION['cart']->contents[$id]['qty']--;

  	$products_price = getSinglePrice($id) * $_SESSION['cart']->contents[$id]['qty'];
		
		$ajax->assign('cost_'.$id, 'innerHTML', $price->format((is_season($id) > 1 ? $products_price*is_season($id):$products_price), true));
		$ajax->assign('qty_'.$id, 'value', $_SESSION['cart']->contents[$id]['qty']);
		
		$check = checkStock($id);
		if(empty($check['info']) && !$check['this']) {
			$ajax->script('$("#p_n_'.clean($id).' .products_out_of_stock").remove();');
			$ajax->script('$(".headerInfo").fadeOut(900,function(){$(this).remove();});');
		}
		
		$ajax->call('xajax_singlePrice', $id);
		
		if(!empty($_SESSION['cart']->contents[$id]['attributes']))
			$ajax->call('xajax_attrPrice', $id);
		
		$ajax->call('xajax_calculateTotal');

	} elseif($_SESSION['cart']->count_contents() >= 1) {
		$_SESSION['cart']->remove($id);
		$check = checkStock($id);
		if(!$check['info'] && !$check['this'])
			$ajax->script('$(".headerInfo").fadeOut(900,function(){$(this).remove();});');
		$id = get_clean_id($id);
		$ajax->script('$EL(".p_'.$id.'").fadeOut(900,function(){$(this).remove();});');
		$ajax->call('xajax_calculateTotal');
		$ajax->call('xajax_calculateShippingTime');

	} else {
		$_SESSION['cart']->reset();
		$ajax->script('$(".headerInfo").fadeOut(900,function(){$(this).remove();});');
		$ajax->assign('cart_quantity', 'innerHTML', '<div id="cart_is_empty">'.CART_IS_EMPTY.'</div>');
		$ajax->call('xajax_calculateShippingTime');
	}

	$ajax->call('xajax_removeLoader');

	return $ajax;
}

function is_season($id) {
	global $price;
	
	if($_price = $price->GetGroupPrice($id, $_SESSION['cart']->contents[$id]['qty']) && ($_SESSION['customers_status']['customers_status_graduated_prices'] == 1))
		return $_SESSION['cart']->contents[$id]['qty'];
	else
		return 1;
}

function getSinglePrice($id) {
	global $price;
	
	$product = array_get_item($_SESSION['cart']->products, 'id', $id);
	return $product['price'];
//	$products_price = $price->GetPrice($id, false, 1, get_tax_class_id($id));
//	return $products_price;
}

function singlePrice($id) {
	global $price;
	$ajax = new xajaxResponse();
	$ajax->assign('s_cost_'.$id, 'innerHTML', $price->format(getSinglePrice($id), true));
	return $ajax;
}

function plus($id) {
	global $price;
	$ajax = new xajaxResponse();

	if($_SESSION['cart']->contents[$id]['qty'] > 0)
		$_SESSION['cart']->contents[$id]['qty']++;
	else {
		preg_match("/([0-9]*)\{([0-9]*)\}([0-9]*)/", $id, $Treffer);
		if(!empty($Treffer[2]) && !empty($Treffer[3]))
			$_SESSION['cart']->add_cart($Treffer[1], 1, array($Treffer[2] => $Treffer[3]));
		else
			$_SESSION['cart']->add_cart($id);
	}

	$ajax->call('xajax_calculateTotal');
	
	$check = checkStock($id);
	if(!empty($check['info'])) {
		$ajax->script('if($(".headerInfo").length < 1){$(".mainbody").prepend("<div class=\"headerInfo\">'.$check['info'].'</div>").hide();}');
		$ajax->script('$(".mainbody").fadeIn(900);');
		if($check['this'])
			$ajax->script('if($("#p_n_'.clean($id).' .products_out_of_stock").length < 1){$("#p_n_'.clean($id).'").append(\''.$check['out'].'\')}');
	}
	
	if(!empty($_SESSION['cart']->contents[$id]['attributes']))
		$ajax->call('xajax_attrPrice', $id);
	
	$ajax->call('xajax_singlePrice', $id);

	$products_price = getSinglePrice($id) * $_SESSION['cart']->contents[$id]['qty'];
	$ajax->assign('cost_'.$id, 'innerHTML', $price->format((is_season($id) > 1 ? $products_price*is_season($id):$products_price), true));
	$ajax->assign('qty_'.$id, 'value', $_SESSION['cart']->contents[$id]['qty']);

	$ajax->call('xajax_removeLoader');

	return $ajax;
}

function clean($id) {
	return str_replace('}', '-', str_replace('{', '-', $id));
}

function attrPrice($id) {
	global $price;
	$ajax = new xajaxResponse();
	
	foreach($_SESSION['cart']->contents[$id]['attributes'] AS $option => $value) {
		$attr_price = $price->GetOptionPrice(get_prid($id), $option, $value);
		$ajax->assign('a_q_'.get_prid($id).'_'.$option.'_'.$value, 'innerHTML', '<em>'.$_SESSION['cart']->contents[$id]['qty'].'x</em>');
		$ajax->assign('a_t_'.get_prid($id).'_'.$option.'_'.$value, 'innerHTML', '<em>'.get_attribute_prefix($option, $value).$price->format($attr_price['price']*$_SESSION['cart']->contents[$id]['qty'], true).'</em>');
		
	}
	
	$ajax->assign('ts_'.clean($id), 'innerHTML', $price->format($price->GetPrice($id, false, $_SESSION['cart']->contents[$id]['qty'], get_tax_class_id($id))+$price->format($_SESSION['cart']->attributes_price($id)*$_SESSION['cart']->contents[$id]['qty'], false), true));
	
	return $ajax;
}

function calculateShippingTime() {
	$ajax = new xajaxResponse();
  $max_shipping_time_ranking = 0;
	
	$products = $_SESSION['cart']->get_products();
  for($idx = 0; $idx < count($products); $idx++) {
  	$max_shipping_time_ranking = max($max_shipping_time_ranking, get_shippingtime_rank('name', $products[$idx]['shipping_time']));
  }
  $shipping_time_name = get_shippingtime_name('ranking', $max_shipping_time_ranking);

//  echo $shipping_time_name;
  $ajax->assign('shipping_time', 'innerHTML', $shipping_time_name);

	return $ajax;
}


function calculateTotal() {
	global $price, $order, $db;

	$ajax = new xajaxResponse();
	$ot_total = $price->_ext->get_total_values();
	$total_content = '';
	
  require(DIR_WS_CLASSES.'class.order_total.php');
  $order_total_modules = new order_total();
  $order_total_modules->values_from_cart = true;
  $total_content_array = $order_total_modules->process(array('ot_subtotal', 'ot_tax', 'ot_total'));

	$ajax->assign('totalcost_ot_subtotal', 'innerHTML', $total_content_array['ot_subtotal']['text']);
  foreach($total_content_array as $k => $content) {
    if ($content['code'] == 'ot_tax')
    	$ajax->assign('totalcost_'.$k, 'innerHTML', $content['text']);
  }
	$ajax->assign('totalcost_ot_total_netto', 'innerHTML', $price->format($total_content_array['all']['netto'], true));

return $ajax;
  echo_e($total_content_array, 'E');

	$_SESSION['cart']->get_products(true);
	$total = $_SESSION['cart']->show_total();
	$total_netto = $_SESSION['cart']->show_total();


	if ($_SESSION['customers_status']['customers_status_show_price'] == '1') {
  	$ajax->script('$(".ot_subtotal").html("'.SUB_TITLE_SUB_TOTAL.' '.$price->format($ot_total['ot_sum_products']['price']+$price->_ext->sum_tax($ot_total['ot_sum_products']['tax']), true).'");');

    $ot_discounts_content = '';
    foreach($ot_total['ot_discounts'] as $k => $v) {
      if ($k != '_all') {
        if ($ot_discounts_content != '') $ot_discounts_content .= '</br>';
        $ot_discounts_content 
          .= number_format($v['rate'],1,',','.').$v['name'] . ': -'
            . $price->format($v['price']+$price->_ext->sum_tax($v['tax']), true);
      }
    }
  	$ajax->script('$(".ot_discount").html("'.$ot_discounts_content.'");');

		$ajax->script('$(".ot_netto").html("Netto: '.$price->format($ot_total['ot_sum']['price'], true).'")');

    $ot_taxes_content = '';
    foreach($ot_total['ot_taxes'] as $k => $v) {
      if ($k != '_all') {
        if ($ot_taxes_content != '') $ot_taxes_content .= '</br>';
        $ot_taxes_content .= $v['name'] . ': ' . $price->format($v['rate'], true);
      }
    }
  	$ajax->script('$(".ot_tax").html("'.$ot_taxes_content.'");');
    $ajax->script('$(".ot_total").html("'.SUB_TITLE_TOTAL.' '.$price->format($ot_total['ot_sum']['full'], true).'");');

	} else
		$total_content .= '<div class="ot_subtotal">'.NOT_ALLOWED_TO_SEE_PRICES.'</div>';


	if ($customer_status_value['customers_status_ot_discount'] != 0)
		$total_content .= TEXT_CART_OT_DISCOUNT.$customer_status_value['customers_status_ot_discount'].'%';

	
	if(!isset($order->delivery['country']['iso_code_2']) || $order->delivery['country']['iso_code_2'] == '') {
		unset($_SESSION['shipping']);
		
		$selected = isset($_SESSION['customer_country_id']) ? $_SESSION['customer_country_id'] : STORE_COUNTRY;
		require_once(DIR_FS_INC.'inc.get_country_list.php');
		if (!isset($_SESSION['customer_id']) && sizeof(get_countriesList()) > 1) {
			if (isset($_SESSION['country']))
				$selected = $_SESSION['country'];
			else
				$selected = STORE_COUNTRY;
		}
		
		$delivery_zone = $db->db_query("SELECT 
											countries_id, 
											countries_iso_code_2, 
											countries_name 
										FROM 
											".TABLE_COUNTRIES." 
										WHERE 
											countries_id = ".$selected);
		$order->delivery['country']['iso_code_2'] = $delivery_zone->fields['countries_iso_code_2'];
		$order->delivery['country']['title'] = $delivery_zone->fields['countries_name'];
		$order->delivery['country']['id'] = $delivery_zone->fields['countries_id'];
	}
	
	$_SESSION['delivery_zone'] = $order->delivery['country']['iso_code_2'];
	require(DIR_FS_INC.'inc.free_shipping.php');
	require(DIR_WS_CLASSES.'class.shipping.php');
	$shipping = new shipping();
	$quotes = $shipping->quote();
	
	$total = $_SESSION['cart']->show_total();
	
	foreach ($quotes AS $quote) {
    if ($quote['id'] != 'freeamount') {
      $quote['methods'][0]['cost'] = $price->CalculateCurr($quote['methods'][0]['cost']);
      $total += ((isset($quote['tax']) && $quote['tax'] > 0) ? $price->AddTax($quote['methods'][0]['cost'],$quote['tax']) : (!empty($quote['methods'][0]['cost']) ? $quote['methods'][0]['cost'] : '0'));
      $i++;
    }
  }
	unset($_SESSION['delivery_zone']);
	
	if(1==2 && !empty($total))
    	$ajax->script('$(".ot_total").html("Summe: '.$price->format($total, true).'");');
	
	return $ajax;
}

function checkStock($id) {
	$check = '';
	$msg = '';
	$this_p = false;
	
	require_once(DIR_FS_INC.'inc.check_stock.php');
	
	reset($_SESSION['cart']->contents);
	while(list($products_id,) = each($_SESSION['cart']->contents)) {
		$check .= check_stock($products_id, $_SESSION['cart']->contents[$products_id]['qty']);
		if(get_prid($id) == $products_id && !empty($check))
			$this_p = true;
			
		if(1==2 && !empty($_SESSION['cart']->contents[$products_id]['attributes'])) {
			while(list($o_id,) = each($_SESSION['cart']->contents[$products_id]['attributes'])) {
				$check .= check_stock_attributes($o_id, $_SESSION['cart']->contents[$products_id]['qty']);
			}
		}
	}
	
	if(!empty($check)) {
		if(STOCK_ALLOW_CHECKOUT == 'true')
			$msg = OUT_OF_STOCK_CAN_CHECKOUT;
		else
			$msg = OUT_OF_STOCK_CANT_CHECKOUT;
	}
	return array('this' => $this_p, 'out' => $check, 'info' => $msg);
}

if(!is_object($xajax))
	$xajax = new xajax();

$xajax->registerFunction("deleteFromCart");
$xajax->registerFunction("plus");
$xajax->registerFunction("minus");
$xajax->registerFunction("delete");
$xajax->registerFunction("attrPrice");
$xajax->registerFunction("singlePrice");
$xajax->registerFunction("calculateTotal");
$xajax->registerFunction("calculateShippingTime");
?>